package user

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"weekly-exam/config"
	"weekly-exam/internal/model/dao"
)

type AddFriends struct {
	UserName string `form:"userName" json:"userName" xml:"userName" binding:"required"`
	UserId   int    `form:"userId" json:"userId" xml:"userId" binding:"required"`
}

func AddFriend(c *gin.Context) {
	var json AddFriends
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	userName := json.UserName
	userId := json.UserId
	var user dao.User
	config.DB.Where("user_name=?", userName).First(&user)
	if user.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "没有该用户"})
		return
	}
	//有的话就是添加好友，但是双方得同时添加为好友
	friend := dao.Friend{
		UserId:    userId,
		FriendId:  int(user.ID),
		UserName:  user.UserName,
		NickName:  user.NickName,
		HeadImage: user.HeadImage,
		Intro:     user.Intro,
	}
	config.DB.Create(&friend)
	//对方也得有你的好友
	var users dao.User
	config.DB.Where("id=?", userId).First(&users)
	d := dao.Friend{
		UserId:    int(user.ID),
		FriendId:  userId,
		UserName:  users.UserName,
		NickName:  users.NickName,
		HeadImage: user.HeadImage,
		Intro:     users.Intro,
	}
	config.DB.Create(&d)
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "添加成功",
	})
}
